import json

import pika
from pika.exchange_type import ExchangeType

URL = "iot.mq.rabbit.ztn-tech.com"
PORT = 5672
USER_NAME = "test"
PASSWORD = "Ztn654321"
EXCHANGE_NAME = "ztn.iot.sdk"
QUEUE_BASE_NAME = EXCHANGE_NAME+"."
IS_DURABLE = True

def connect(topic, fun):
    queueName = QUEUE_BASE_NAME + topic
    credentials = pika.PlainCredentials(username=USER_NAME, password=PASSWORD)
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host=URL, port=PORT, virtual_host='/', credentials=credentials))
    channel = connection.channel()
    channel.exchange_declare(exchange=EXCHANGE_NAME, exchange_type=ExchangeType.topic, durable=true)
    # 申明消息队列，消息在这个队列传递，如果不存在，则创建队列
    channel.queue_declare(queue=queueName, durable=IS_DURABLE, exclusive=False, auto_delete=!IS_DURABLE)
    channel.queue_bind(queue=queueName, exchange=EXCHANGE_NAME, routing_key=topic)

    # 定义一个回调函数来处理消息队列中的消息，这里是打印出来
    def callback(ch, method, properties, body):
        ch.basic_ack(delivery_tag=method.delivery_tag)
        fun(method.exchange, json.loads(body.decode()))

    # 告诉rabbitmq，用callback来接收消息
    channel.basic_consume(queueName, callback)
    # 开始接收信息，并进入阻塞状态，队列里有信息才会调用callback进行处理
    channel.start_consuming()
